package com.cry.app.core.hibernate;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import com.cry.todo.domain.User;

public class MultiEntities {

	public static List getEntities(Class<?> clazz ,ArrayList<Integer> ids, List list) throws Exception{
		
		if(list == null) {
			list = new ArrayList();
		}
		
		//if(list == null) return null;
		System.out.println(" (0) " + ids + " - " + list);

		/**
		 * Delete items not in ids array
		 * Not foreach because of concurent modification exception 
		 */
		LinkedList tmpLinkedList = new LinkedList(list);
		for(Iterator iter = tmpLinkedList.iterator(); iter.hasNext(); ) {
			MultiEntity record = (MultiEntity) iter.next();
			if(!ids.contains(record.getId())) {
				System.out.println(" (-) " + record.getId());
				iter.remove();
			}  
			ids.remove(new Integer(record.getId()));
		}
		list.clear();
		list.addAll(tmpLinkedList);

		/**
		 * Insert new items not in original db
		 */
		for(Integer id : ids) {
			MultiEntity record = (MultiEntity) clazz.newInstance();
			record.setId(id);
			System.out.println(" (+) " + record.getId());
			list.add(record);
		}
		System.out.println(" (=) " + ids + " - " + list);
		return list;
	}

}
